/*
 * App.java
 * Describe SWF
 *
 * A browser for Flash files.
 * Copyright (c) 2001-2006 Flagstone Software Ltd. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 * 
 * For more information please contact:
 * 
 * Stuart MacKay
 * Flagstone Software Ltd
 * 92 High Street
 * Wick, Caithness KW1 4LY
 * Scotland
 * 
 * www.flagstonesoftware.com
 */
package com.flagstone.describe;

import java.text.*;
import java.util.*;
import java.util.logging.*;
import java.io.*;
import java.net.URL;
import java.awt.*;

import javax.swing.*;

class App
{
    static final String AppName = "describe";
    
    static App sharedInstance = null;

    private static final int LogFileSize = 1048576;
    private static final int LogFileCount = 4;
    
    static synchronized App getInstance()
    {
        if (sharedInstance == null)
            sharedInstance = new App();
        
        return sharedInstance;
    }

    public static void main(String args[])
    {
        App.getInstance().init();
    }
    
    private boolean isWindows;
    private boolean isMac;
 
    private File userDir;
    private Locale currentLocale;
    private Logger logger = null;
    private ResourceBundle strings = null;
    
    private Image icon = null;
    
    private boolean appDidInit = true;
    
    App()
    {
        userDir = new File(System.getProperty("user.home"), "."+AppName);
        
        currentLocale = Locale.getDefault();
        
        logger = Logger.getLogger(AppName);      
        logger.setLevel(Level.ALL);       
    }
    
    Image getIcon()
    {
        return icon;
    }
    
    void init()
    {
        initAppDir();
        initLogFiles();
        initStringsTable();
        initUserInterface();
        
        URL iconFile = getClass().getResource("/"+App.AppName+".png");
        icon = new ImageIcon(iconFile).getImage();

        Preferences.getInstance();
        
        showSplashPanel();
        openDocument();
          
        if (appDidInit == false)
        {
            String message = "Could not start Describe";
            JOptionPane.showMessageDialog(null, message, null, JOptionPane.ERROR_MESSAGE);
            quit();
        }
    }
    
    boolean isWindows()
    {
        return isWindows;
    }
    boolean isMac()
    {
        return isMac;
    }
    
    String localizedString(String keyName)
    {
        return localizedString(keyName, new Object[] {} );
    }
    String localizedString(String keyName, String argument)
    {
        return localizedString(keyName, new Object[] { argument });
    }
    String localizedString(String keyName, Object[] arguments)
    {
        String formattedString = "";

        try 
        {
            String value = strings.getString(keyName);
            formattedString = MessageFormat.format(value, arguments);
        }
        catch (Exception e) 
        {   
            String message = "Could not create localized string for key: " + keyName;
            logger.warning(message);
        }
        return formattedString;
    }

    private void initAppDir()
    {
        if (userDir.exists() && userDir.isFile())
        {
            if (userDir.delete() == false)
                logger.warning("Could not delete application file: "+userDir.getPath());
        }
        
        
        if (userDir.exists() == false)
        {
            if (userDir.mkdir() == false)
                logger.warning("Could not create application directory: "+userDir.getPath());
        }
    }
    private void initLogFiles()
    {
        FileHandler handler = null;
        String pattern = null;

        try
        {
            if (userDir.exists())
                pattern = "%h/."+AppName+"/"+AppName+"%g.log";
            else
                pattern = "%t/"+AppName+"%g.log";
                        
            handler = new FileHandler(pattern, LogFileSize, LogFileCount);
            logger.addHandler(handler);
        }
        catch (IOException e)
        {
            logger.severe("Could not create log files with pattern: "+pattern);
            appDidInit = false;
        }
    }
    private void initStringsTable()
    {
        try
        {
            strings = ResourceBundle.getBundle("strings", currentLocale);
        }
        catch (MissingResourceException e)
        {
            String message = "Could not load the file: strings.properties";
            logger.severe(message);
            appDidInit = false;
        }
    }
    private void initUserInterface()
    {
        isWindows = (System.getProperty("os.name").indexOf("Windows") >= 0);
        isMac = (System.getProperty("os.name").indexOf("Mac OS X") >= 0);

        try
        {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (Exception e)
        {
            logger.severe("Could not set the look & feel of the user interface");
            appDidInit = false;
        }
    }
    private void showSplashPanel()
    {
        String filename = localizedString("Application.image");
        URL path = App.class.getResource(filename);              
        SplashPanel panel = new SplashPanel(new ImageIcon(path));
        
        try 
        {
            panel.show();           
            synchronized (this) {
                wait(3000);
            }
        } 
        catch(Exception e) {
        }
        panel.hide();
    }
    
    void openDocument()
    {
        Document.newDocument();        
    }
    
    void quit() 
    {
        Preferences.getInstance().savePreferences();
        System.exit(0);
    }
}
